package com.bingquan.company.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringBeanUtil implements ApplicationContextAware {

    // 这是一个工具类， 因为getBeanByName（）方法一般是静态的， 所有该变量静态， 且静态可以项目启动时候加载
    private static ApplicationContext applicationContext;

    /**
     * setApplicationContext 会在SpringBeanUtil bean初始化后自动注入执行，  归spring管理
     * 可参考： https://blog.csdn.net/u011485376/article/details/82633661
     *
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 可获取 SpringBeanUtil类同一上下文中所有bean
     *
     * @param beanName
     * @return
     */
    public static Object getBeanByName(String beanName) {
        return applicationContext.getBean(beanName);
    }
}
